package com.cole.miniapp.project.annotation.support;

import com.cole.miniapp.common.exception.AuthorizationExtendException;
import com.cole.miniapp.common.utils.SpringUtils;
import com.cole.miniapp.project.annotation.LoginStore;
import com.cole.miniapp.project.domain.FcmBusiness;
import com.cole.miniapp.project.service.StoreAuthService;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Date;

/**
 * 方法拦截器
 * 
 * @author cole
 *
 */
public class LoginStoreHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	public static final String USER_LOGIN_TOKEN = "X-Login-Token";

	public static final String USER_ID = "X-User-Id";

	public static final String STORE_ID = "X-Store-Id";

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(LoginStore.class);
	}

	@Override
	public FcmBusiness resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request,
									   WebDataBinderFactory factory) throws Exception {
		boolean required = parameter.getParameterAnnotation(LoginStore.class).required();
		String token = request.getHeader(USER_LOGIN_TOKEN);
		String userId= request.getHeader(USER_ID);
		String storeId= request.getHeader(STORE_ID);

		if (required && (token == null || token.isEmpty()||userId == null || userId.isEmpty()|| storeId==null|| storeId.isEmpty())) {
			// 没有传递抛出异常，由外层拦截来进行响应
			throw new AuthorizationExtendException();
		}

		StoreAuthService storeAuthService=SpringUtils.getBean(StoreAuthService.class);
		FcmBusiness fcmBusiness=storeAuthService.selectBusinessByKey(token,Long.valueOf(userId),Long.valueOf(storeId));

		if (required && (fcmBusiness == null )) {
			throw new AuthorizationExtendException();
		}

		if (required && (fcmBusiness.getState().equals(1))) {
			throw new AuthorizationExtendException();
		}

		return fcmBusiness;
	}


	// controller调用举例,required为true系统若无登录态，系统强制返回401，不会执行controller代码，若为false表示可有可无，系统不会强制处理，没有就返回null
	/*
	 * @PostMapping(value = "/xxx1") public ResponseResult
	 * userCheckMyCoupon1(@LoginUser(required=true) List<WgtUser> user,String
	 * name){
	 * 
	 * }
	 * 
	 * @PostMapping(value = "/xxx2") public ResponseResult
	 * userCheckMyCoupon2(@LoginUser(required=false) List<WgtUser> user,String
	 * name){
	 * 
	 * }
	 */
}
